package com.ywy.controller.pay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.ywy.config.AlipayConfig;
import com.ywy.entity.User;
import com.ywy.service.UserService;
import com.ywy.utils.DateUtil;
import com.ywy.utils.DeviceUtil;
import com.ywy.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付宝支付Controller
 */
@Slf4j
@Controller
@RequestMapping("alipay")
public class AlipayController {
    @Value("${system.vipMoney}")
    private String vipMoney;

    @Resource
    private AlipayConfig alipayConfig;
    @Resource
    private UserService userService;

    /**
     * 支付请求
     *
     * @param request
     * @param response
     * @param session
     * @throws Exception
     */
    @RequestMapping("pay")
    public void pay(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        try {
            User user = (User) session.getAttribute("currentUser");
            String username = user.getUsername(); // 获取用户名
            String orderNo = username + "-" + DateUtil.formatDatePure(); // 生成订单号  用户名+日期格式

            String result = "";
            String userAgent = request.getHeader("user-agent");
            // 封装请求客户端
            AlipayClient client = new DefaultAlipayClient(alipayConfig.getUrl(), alipayConfig.getAppid(), alipayConfig.getPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(), alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType());

            // 移动设备支付请求
            if (DeviceUtil.isMobileDevice(userAgent)) {
                AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
                alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
                alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
                AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
                model.setProductCode("FAST_INSTANT_TRADE_PAY"); // 销售产品码
                model.setOutTradeNo(orderNo); // 订单号
                model.setSubject("购买资源共享平台VIP会员"); // 订单名称
                model.setTotalAmount(vipMoney); // 支付总金额
                model.setBody("尊贵资源共享平台VIP会员 你值得拥有！"); // 商品描述
                alipayRequest.setBizModel(model);
                log.info("支付宝请求参数：{}", alipayRequest.getTextParams());
                result = client.pageExecute(alipayRequest).getBody(); // 发送请求
            } else {//网页支付请求
                AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
                alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
                alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
                AlipayTradePayModel model = new AlipayTradePayModel();
                model.setProductCode("FAST_INSTANT_TRADE_PAY"); // 销售产品码
                model.setOutTradeNo(orderNo); // 订单号
                model.setSubject("购买资源共享平台VIP会员"); // 订单名称
                model.setTotalAmount(vipMoney); // 支付总金额
                model.setBody("尊贵资源共享平台VIP会员 你值得拥有！"); // 商品描述
                alipayRequest.setBizModel(model);
                log.info("支付宝请求参数：{}", alipayRequest.getTextParams());
                result = client.pageExecute(alipayRequest).getBody(); // 发送请求
            }
            log.info("支付宝响应结果：{}", result);

            response.setContentType("text/html;charset=" + alipayConfig.getCharset());
            response.getWriter().write(result); // 直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝服务器同步通知页面
     *
     * @param request
     */
    @RequestMapping("payResult")
    public ModelAndView payResult(HttpServletRequest request) {
        try {
            ModelAndView mav = new ModelAndView();
            //获取支付宝GET请求过来的信息
            Map<String, String[]> requestParams = request.getParameterMap();
            log.info("支付宝服务器同步通知：{}", requestParams);
            Map<String, String> params = new HashMap<>();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = iter.next();
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }

            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());

            if (signVerified) {
                mav.addObject("message", "充值VIP成功，请重新登录生效，然后联系管理员（QQ:11223344），领取会员福利！");
            } else {
                mav.addObject("message", "验签失败，请联系管理员(QQ:11223344)");
            }
            mav.setViewName("vip/payResult");
            return mav;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 支付宝服务器异步通知
     *
     * @param request
     * @return
     */
    @RequestMapping("payNotify")
    public void payNotify(HttpServletRequest request) {
        try {
            //获取支付宝GET过来反馈信息
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            log.info("支付宝服务器异步通知：" + requestParams);
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = iter.next();
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
                System.out.println("name:" + name + ",valueStr:" + valueStr);
            }

            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());
            //商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            //交易状态
            String trade_status = request.getParameter("trade_status");

            // 验证成功 更新订单信息
            if (signVerified) {
                if (trade_status.equals("TRADE_FINISHED")) {
                    log.info("TRADE_FINISHED");
                }
                if (trade_status.equals("TRADE_SUCCESS")) {
                    log.info("TRADE_SUCCESS");
                }
                if (StringUtil.isNotEmpty(out_trade_no)) {
                    String username = out_trade_no.split("-")[0];
                    User user = userService.getByUsername(username);
                    user.setVip(true);
                    user.setPoints(1000000);
                    userService.save(user);
                }
            } else {
                log.error("验证未通过");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
